package com.aoip.telemetry.telemetry.receive.session;

import io.netty.channel.Channel;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用于缓存测站与
 * @author chenbai
 * @version 1.0
 * @date 2021/8/7 11:13
 */
public class SessionMemoryImpl implements Session {
    private final Map<String, Channel> usernameChannelMap = new ConcurrentHashMap<>();
    private final Map<Channel, String> channelUsernameMap = new ConcurrentHashMap<>();
    private final Map<Channel, Map<String, Object>> channelAttributesMap = new ConcurrentHashMap<>();

    @Override
    public void bind(Channel channel, String stCode) {
        usernameChannelMap.put(stCode, channel);
        channelUsernameMap.put(channel, stCode);
        channelAttributesMap.put(channel, new ConcurrentHashMap<>());
    }

    @Override
    public void unbind(Channel channel) {
        String stCode = channelUsernameMap.remove(channel);
        if (StringUtils.hasText(stCode)) {
            usernameChannelMap.remove(stCode);
        }
        if (channel != null) {
            channelAttributesMap.remove(channel);
        }
    }

    @Override
    public Object getAttribute(Channel channel, String key) {
        Map<String, Object> map = channelAttributesMap.get(channel);
        if (map != null) {
            return map.get(key);
        }
        return "";
    }

    @Override
    public void setAttribute(Channel channel, String key, Object value) {
        Map<String, Object> map = channelAttributesMap.get(channel);
        if (map == null) {
            return;
        }
        map.put(key, value);
    }

    @Override
    public Channel getChannel(String stCode) {
        return usernameChannelMap.get(stCode);
    }
}
